from django.contrib.auth import models
from django.contrib.auth.models import Group, User
from django.db.models import fields
# Create your models here.
from rest_framework import serializers

from drf.models import Demo


# Serializer  必须实现created  和 update 方法
class DemoSerializer(serializers.Serializer):
    name = serializers.CharField(max_length=255, min_length=2)
    age = serializers.IntegerField(min_value=10, max_value=99)

    def create(self, validated_data):
        return Demo.objects.create(**validated_data)

    def update(self, instance, validated_data):
        instance.name = validated_data.get('name', instance.name)
        instance.age = validated_data.get('age', instance.age)
        instance.save()
        return instance

    def validate(self, attrs):
        if attrs.get('name') and 'xxx' in attrs.get('name'):
            return attrs
        else:
            raise serializers.ValidationError("name 必须包含 xxx")

# ModelSerializer 减少代码冗余
class Demo1Serializer(serializers.ModelSerializer):
    class Meta:
        model = Demo
        fields = ['id', 'name', 'age']

    def validate(self, attrs):
        if attrs.get('name',False) and  "xxx"  not in attrs.get('name'):
           raise serializers.ValidationError("name ：必须包含 xxx")
        elif attrs.get('age',0)<10 or attrs.get('age',0)>100:
           raise serializers.ValidationError("age 必须范围10-100")   
        else:
            return attrs    


class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ['url', 'username', 'email', 'groups']


class GroupSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Group
        fields = ['url', 'name']
